/**
 * 网络请求封装
 */

const BASE_URL = 'http://localhost:8082/api';

const request = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: /^https?:\/\//.test(options.url) ? options.url : (BASE_URL + options.url),
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          const data = res.data;
          const hasCode = data && Object.prototype.hasOwnProperty.call(data, 'code');
          if (!hasCode) {
            resolve(data);
            return;
          }
          if (data.code === 200 || data.code === 0 || data.success === true) {
            resolve(data);
          } else {
            uni.showToast({
              title: data.message || data.msg || '请求失败',
              icon: 'none',
              duration: 2000
            });
            reject(data);
          }
        } else {
          uni.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
          reject(res);
        }
      },
      
      fail: (err) => {
        console.error('请求失败：', err);
        uni.showToast({
          title: '网络连接失败，请检查网络',
          icon: 'none',
          duration: 2000
        });
        reject(err);
      }
    });
  });
};

export const get = (url, data = {}) => {
  return request({ url, method: 'GET', data });
};

export const post = (url, data = {}) => {
  return request({ url, method: 'POST', data });
};

export const put = (url, data = {}) => {
  return request({ url, method: 'PUT', data });
};

export const del = (url, data = {}) => {
  return request({ url, method: 'DELETE', data });
};

export default request;



